from oemlist import Ui_oemlist
from PyQt4 import QtCore, QtGui
import parseoem
import paramiko

class Tabelaoem(QtGui.QDialog):
    def __init__(self, parent,transport,oem):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_oemlist()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.btsair_gravar, QtCore.SIGNAL("clicked()"), self.sair_gravar)
        QtCore.QObject.connect(self.ui.btcancelar, QtCore.SIGNAL("clicked()"), self.cancelar)
        self.ui.tabela.setColumnWidth(0,200)
        self.ui.tabela.setColumnWidth(1,200)
        self.transport = transport
        sftp = paramiko.SFTPClient.from_transport(self.transport)
        self.oem = oem
        parse = parseoem.Parseoem(sftp,self.oem)
        lista = parse.makechunklist(parse.getfile())
        l2 = []
        for ck in lista:
            l2 += ck.gettuples()
            l2.append(('---','-----'))
        cont = len(l2)
        self.ui.tabela.setRowCount(cont)
        for i in range(cont):
            var = QtGui.QTableWidgetItem(l2[i][0])
            valor = QtGui.QTableWidgetItem(l2[i][1])
            self.ui.tabela.setVerticalHeaderItem(i,var)
            self.ui.tabela.setItem(i,0,valor)
        sftp.close()

    def sair_gravar(self):
        sftp = paramiko.SFTPClient.from_transport(self.transport)
        parse = parseoem.Parseoem(sftp,self.oem)
        id = '1' if self.oem <> 'OEMApplication.txt' else '0'
        cont = self.ui.tabela.rowCount()
        for i in range(cont):
            valor = str(self.ui.tabela.item(i,0).text())
            var = str(self.ui.tabela.takeVerticalHeaderItem(i).text())
            if var == '---':
                if id <> '0':
                    id = str(int(id) + 1)
            else:
                if id <> '0':
                    parse.setparam(var,valor,id)
                else:
                    parse.setparam(var,valor)

        parse.setfile()
        sftp.close()
        self.close()

    def cancelar(self):
        self.close()
